﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Windows.Data;
using System.ComponentModel;
using EIA.SLClient.Utility.Controls;
using System.Collections.ObjectModel;
using EIA.Basic.Model;

namespace EIA.SLClient.PlatManage.BasicMgr
{
    public class DepartmentTreeViewModel : SimpleMvvmToolkit.ViewModelBase<DepartmentTreeViewModel>
    {
        public DepartmentTreeViewModel()
        {
            this.RegisterToReceiveMessages(EIA.SLClient.PlatManage.Infrastructure.MessageTokens.DEPARTMENT_RETRIEVE, EP_Retrieve);
            this.RegisterToReceiveMessages<TreeNode>(EIA.SLClient.PlatManage.Infrastructure.MessageTokens.DEPARTMENT_NEW_CANCEL, EP_NewCancel);
        }

        private void EP_Retrieve(object sender, SimpleMvvmToolkit.NotificationEventArgs e)
        {
            RetrieveItems();
        }
        private void EP_NewCancel(object sender, SimpleMvvmToolkit.NotificationEventArgs<TreeNode> e)
        {
            if (e.Data == null) return;
            var p = e.Data.GetParent(DepartmentRootNodes);
            if (p == null) DepartmentRootNodes.Remove(e.Data);
            else p.Children.Remove(e.Data);
        }

        private void Busy(string msg = "等待...")
        {
            IsBusy = true;
            SendMessage<bool>(EIA.SLClient.PlatManage.Infrastructure.MessageTokens.DEPARTMENT_BUSY_STATE, new SimpleMvvmToolkit.NotificationEventArgs<bool>(msg, true));
        }

        private void Free()
        {
            IsBusy = false;
            SendMessage<bool>(EIA.SLClient.PlatManage.Infrastructure.MessageTokens.DEPARTMENT_BUSY_STATE, new SimpleMvvmToolkit.NotificationEventArgs<bool>("", false));
        }

        #region notifyprop

        protected bool _IsBusy;
        /// <summary>
        /// 
        /// </summary>
        public bool IsBusy
        {
            get { return _IsBusy; }
            set
            {
                _IsBusy = value;
                NotifyPropertyChanged(m => m.IsBusy);
            }
        }

        protected ObservableCollection<TreeNode> _DepartmentRootNodes;
        public ObservableCollection<TreeNode> DepartmentRootNodes
        {
            get { return _DepartmentRootNodes; }
            set
            {
                _DepartmentRootNodes = value;
                NotifyPropertyChanged(m => m.DepartmentRootNodes);
            }
        }
        private TreeNode _SelectedNode;
        public TreeNode SelectedNode
        {
            get { return _SelectedNode; }
            set
            {
                _SelectedNode = value;
                NotifyPropertyChanged(m => m.SelectedNode);
                UpdateItemCommand.RaiseCanExecuteChanged();
                DeleteItemCommand.RaiseCanExecuteChanged();
            }
        }

        #endregion

        #region command

        #region RetrieveItemsCommand

        private SimpleMvvmToolkit.DelegateCommand _RetrieveItemsCommand = null;
        public SimpleMvvmToolkit.DelegateCommand RetrieveItemsCommand
        {
            get
            {
                if (_RetrieveItemsCommand == null)
                {
                    _RetrieveItemsCommand = new SimpleMvvmToolkit.DelegateCommand(RetrieveItems, CanExcuteRetrieveItems);
                } return _RetrieveItemsCommand;
            }
            set { _RetrieveItemsCommand = value; NotifyPropertyChanged(m => m.RetrieveItemsCommand); }
        }

        public void RetrieveItems()
        {
            EIA.Basic.BLL.ClientProxy.TDepartmentProxy proxy = new Basic.BLL.ClientProxy.TDepartmentProxy();
            Busy();
            proxy.ListAll((lst) =>
            {
                Free();
                if (lst == null) return;
                int c = lst.Count;
                lst = new List<TDepartment>(lst.OrderBy((d) => { return d.OrderId == null ? c++ : d.OrderId.Value; }));
                ObservableCollection<TreeNode> root = new ObservableCollection<TreeNode>();
                Dictionary<int, TreeNode> dic = new Dictionary<int, TreeNode>();
                foreach (var d in lst)
                {
                    dic[d.DepId] = new TreeNode() { Text = d.DepName, Data = d };
                }
                foreach (var n in dic.Values)
                {
                    TDepartment d = n.Data as TDepartment;
                    if (d != null && d.SupId.HasValue) dic[d.SupId.Value].Children.Add(n);
                    else root.Add(n);
                }
                DepartmentRootNodes = root;
            }, (ex) =>
            {
                Free();
                System.Windows.MessageBox.Show("获取部门目录发生错误！", "提示", System.Windows.MessageBoxButton.OK);
            });
            //List<TreeNode> lst = new List<TreeNode>();
            //for (int i = 0; i < 10; i++)
            //{
            //    lst.Add(new TreeNode() { Text = "部门" + i, Data = new TDepartment() { DepId = i, OrderId = i, DepName = "部门" + i } });
            //}

            //DepartmentRootNodes = new ObservableCollection<TreeNode>(lst);
        }

        public bool CanExcuteRetrieveItems()
        {
            return true;
        }

        #endregion

        #region InsertItemCommand

        private SimpleMvvmToolkit.DelegateCommand _InsertItemCommand = null;
        public SimpleMvvmToolkit.DelegateCommand InsertItemCommand
        {
            get
            {
                if (_InsertItemCommand == null)
                {
                    _InsertItemCommand = new SimpleMvvmToolkit.DelegateCommand(InsertItem, CanExcuteInsertItem);
                } return _InsertItemCommand;
            }
            set { _InsertItemCommand = value; NotifyPropertyChanged(m => m.InsertItemCommand); }
        }

        public void InsertItem()
        {
            TDepartment dept = new TDepartment();
            dept.DepName = "新建部门";
            dept.SupId = SelectedNode == null ? null : (int?)((TDepartment)SelectedNode.Data).DepId;
            TreeNode node = new TreeNode(){ Text = dept.DepName, Data = dept};
            if (SelectedNode == null)
            {
                DepartmentRootNodes.Add(node);
            }
            else
            {
                SelectedNode.Children.Add(node);
            }
            
            SendMessage<TreeNode>(EIA.SLClient.PlatManage.Infrastructure.MessageTokens.DEPARTMENT_NEW,
                new SimpleMvvmToolkit.NotificationEventArgs<TreeNode>("", node));
        }

        public bool CanExcuteInsertItem()
        {
            return true;
        }

        #endregion

        #region UpdateItemCommand

        private SimpleMvvmToolkit.DelegateCommand _UpdateItemCommand = null;
        public SimpleMvvmToolkit.DelegateCommand UpdateItemCommand
        {
            get
            {
                if (_UpdateItemCommand == null)
                {
                    _UpdateItemCommand = new SimpleMvvmToolkit.DelegateCommand(UpdateItem, CanExcuteUpdateItem);
                } return _UpdateItemCommand;
            }
            set { _UpdateItemCommand = value; NotifyPropertyChanged(m => m.UpdateItemCommand); }
        }

        public void UpdateItem()
        {
            SendMessage<TreeNode>(EIA.SLClient.PlatManage.Infrastructure.MessageTokens.DEPARTMENT_UPDATE,
                new SimpleMvvmToolkit.NotificationEventArgs<TreeNode>("", SelectedNode));
        }

        public bool CanExcuteUpdateItem()
        {
            return SelectedNode != null;
        }

        #endregion

        #region DeleteItemCommand

        private SimpleMvvmToolkit.DelegateCommand _DeleteItemCommand = null;
        public SimpleMvvmToolkit.DelegateCommand DeleteItemCommand
        {
            get
            {
                if (_DeleteItemCommand == null)
                {
                    _DeleteItemCommand = new SimpleMvvmToolkit.DelegateCommand(DeleteItem, CanExcuteDeleteItem);
                } return _DeleteItemCommand;
            }
            set { _DeleteItemCommand = value; NotifyPropertyChanged(m => m.DeleteItemCommand); }
        }

        public void DeleteItem()
        {
            if (System.Windows.MessageBox.Show(string.Format("确认删除部门 [{0}]", SelectedNode.Text), "提示", System.Windows.MessageBoxButton.OKCancel) != System.Windows.MessageBoxResult.OK) return;

            EIA.Basic.BLL.ClientProxy.TDepartmentProxy proxy = new Basic.BLL.ClientProxy.TDepartmentProxy();
            Busy();
            TreeNode selected = SelectedNode;
            TDepartment d = selected.Data as TDepartment;
            if (d == null) return;
            proxy.Delete(d.DepId, (r) =>
            {
                Free();
                if (r)
                {
                    selected.GetParent(DepartmentRootNodes).Children.Remove(selected);
                }
                else
                {
                    System.Windows.MessageBox.Show("删除部门失败！", "提示", System.Windows.MessageBoxButton.OK);
                }

            }, (ex) =>
            {
                Free();
                System.Windows.MessageBox.Show("删除部门发生错误！", "提示", System.Windows.MessageBoxButton.OK);
            });

        }

        public bool CanExcuteDeleteItem()
        {
            return SelectedNode != null;
        }

        #endregion

        #region DragDropCommand

        private SimpleMvvmToolkit.DelegateCommand<Tuple<TreeNode, TreeNode>> _DragDropCommand = null;
        public SimpleMvvmToolkit.DelegateCommand<Tuple<TreeNode, TreeNode>> DragDropCommand
        {
            get
            {
                if (_DragDropCommand == null)
                {
                    _DragDropCommand = new SimpleMvvmToolkit.DelegateCommand<Tuple<TreeNode, TreeNode>>(DragDrop, CanExcuteDragDrop);
                } return _DragDropCommand;
            }
            set { _DragDropCommand = value; NotifyPropertyChanged(m => m.DragDropCommand); }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="p">
        /// Item1:子节点
        /// Item2:父节点
        /// </param>
        public void DragDrop(Tuple<TreeNode, TreeNode> p)
        {
            ObservableCollection<TreeNode> brothers = null;
            brothers = p.Item2 == null ? DepartmentRootNodes : p.Item2.Children;
            List<TDepartment> lst = new List<TDepartment>();
            TDepartment pt = p.Item2 == null ? null : p.Item2.Data as TDepartment;
            for (int i = 0; i < brothers.Count; i++)
            {
                var n = brothers[i];
                TDepartment d = n.Data as TDepartment;
                d.OrderId = i;
                d.SupId = pt == null ? null : (int?)pt.DepId;
                lst.Add(d);
            }

            EIA.Basic.BLL.ClientProxy.TDepartmentProxy proxy = new Basic.BLL.ClientProxy.TDepartmentProxy();
            Busy();
            proxy.UpdateList(lst, (r) =>
            {
                Free();
                if (r)
                {

                }
                else
                {
                    SendMessage(EIA.SLClient.PlatManage.Infrastructure.MessageTokens.DEPARTMENT_RETRIEVE, new SimpleMvvmToolkit.NotificationEventArgs());
                }
            }, (ex) =>
            {
                Free();
                SendMessage(EIA.SLClient.PlatManage.Infrastructure.MessageTokens.DEPARTMENT_RETRIEVE, new SimpleMvvmToolkit.NotificationEventArgs());
            });
        }

        public bool CanExcuteDragDrop(Tuple<TreeNode, TreeNode> p)
        {
            return true;
        }

        #endregion

        #endregion

        public void OnLoad()
        {
            if (DepartmentRootNodes == null) RetrieveItems();
        }

    }
}